<template>
  <div class="chat-container">
    <div class="chat-sidebar">
      <div class="searchBox">
        <input type="text" placeholder="搜索">
      </div>
      <!-- 聊天人员列表 -->
      <div class="chat-contacts">
        <!-- 示例：使用 v-for 渲染聊天人员列表 -->
        <div class="contact" v-for="contact in contactsList" :key="contact.id" @click="selectContact(contact)"
             :class="{ 'selected': contact.selected }">
          <div class="avatar">
            {{ contact.user_id }}
          </div>
          <div class="name">
            用户{{ contact.user_id }}
            <div class="goodsID">咨询<span style="color: red">{{ contact.goods_id }}</span></div>
          </div>
        </div>
      </div>
    </div>
    <div class="chat-content">
      <!-- 聊天 姓名头部-->
      <div class="TopName" >
        {{ selectedUser.name }}
      </div>
      <!-- 聊天信息界面  中部-->
      <div class="chat-messages">
        <div class="goods"  v-if="goodsTitle==='1'">
          用户正在向您咨询
          <div class="el-icon-goods" style="color: #14a0cb">{{ goodsName }}</div>
          这款商品
        </div>
        <div class="message" v-for="message in Message" :key="message.id">
          <div class="you item" v-if="message.sender_id !== MyId">
            <div class="avatar-msg">{{ message.sender_id }}</div>
            <div class="content" v-if ="message.type ==='text'">{{ message.message }}</div>
            <div class="File" v-else><img :src=" message.message" alt=""></div>
          </div>
          <div class="me item" v-if="message.sender_id === MyId">
            <div class="content" v-if ="message.type ==='text'">{{ message.message }}</div>
            <div class="File" v-else><img :src=" message.message" alt=""></div>
            <div class="avatar-msg">{{ message.sender_id }}</div>
          </div>
        </div>
      </div>
      <!-- 发送信息部分  底部-->
      <div class="sendMsgBox">

        <div class="type" @click="submitFile">发送文件
          <input type="file" id="fileInput" ref="fileInput" style="display: none" @change="handleFileChange">
          <div class="el-icon-files"></div>
        </div>
        <div class="MsgBox"><textarea placeholder="请输入消息..." v-model="newMessage"></textarea>
          <button class="sendButton" @click="sendMessage()">发送</button> <!-- 添加发送按钮 --></div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  chatAdmin,
  getAdminMsg
} from '../../api/Tip'
import {queryGoodsById}
  from '../../api/index'

export default {
  data() {
    return {
      baseURL:'http://192.168.31.214:1006',
      FileURL:'',
      // 你必须登陆admin509的账号
      MyId: '',
      ws: null,
      newMessage: '',// 新消息
      // 模拟数据
      contactsList: [
        {id: '', user_id: '', admin_id: '', goods_id: '', selected: false}
      ],
      selectedUser: {
        id: '',
        name: '',
        goods_id: ''
      },
      Message: [],
      goodsName: '',
      goodsTitle:'0'
    };
  },
  created() {
    this.getMyId()
    this.initRecordsPeople()
  },
  watch: {
    Message: function () {
      this.$nextTick(() => {
        this.scrollToBottom()
      })
    }
  },
  computed:{

  },
  mounted() {
    this.initWebSocket();
  },
  methods: {
    scrollToBottom() {
      const chatMessages = this.$el.querySelector('.chat-messages')
      if (chatMessages) {
        chatMessages.scrollTop = chatMessages.scrollHeight;
      }
    },
    // 选中聊天对象
    selectContact(contact) {

      // 将所有聊天对象的 selected 属性设置为 false
      this.contactsList.forEach(c => c.selected = false);
      // 将被选中的聊天对象的 selected 属性设置为 true
      contact.selected = true;
      // 根据选中的聊天对象获取聊天记录，并更新界面
      console.log('选中了聊天对象:', contact);
      this.goodsTitle = '1'
      this.selectedUser.id = contact.user_id;
      this.selectedUser.goods_id = contact.goods_id
      this.selectedUser.name = contact.user_id
      this.getGoodsById(contact.goods_id)
      this.getRecordsByUserId(contact)
    },
    submitFile() {
      this.$refs.fileInput.click(); // 触发点击事件，打开文件选择对话框
    },
    handleFileChange(event) {
      const fileList = event.target.files;
      // 确保用户选择了文件
      if (fileList.length > 0) {
        // 创建一个 FormData 对象，用于将文件发送到服务器
        const formData = new FormData();

        // 将文件添加到 FormData 对象中
        formData.append('file', fileList[0]);

        // 发送文件到服务器的代码示例（这里需要根据实际情况替换成你的上传接口）
        fetch(this.baseURL+'/upload', {
          method: 'POST',
          body: formData
        })
            .then(response => {
              // 检查响应是否成功
              if (response.ok) {

                return response.json();
              }
              throw new Error('Network response was not ok.');
            })
            .then(data => {
              // 上传成功后，将返回的路径赋值给FileURL
              this.FileURL =this.baseURL + data.result.path;
              this.sendFileToMsg(this.FileURL )
            })
            .catch(error => {
              console.error('There was a problem with the fetch operation:', error);
            });
      } else {
        console.error('No file selected.');
      }
    },
    sendFileToMsg(fileUrl){
      const message = {
        sender_id: this.MyId,
        goods_id: this.selectedUser.goods_id,
        receiver_id: this.selectedUser.id,
        type: 'file',
        message: fileUrl,
      };
      this.ws.send(JSON.stringify(message));
      this.Message.push(message);
    },
    sendMessage() {
      if(this.goodsTitle === '0'){
        this.$message.error("请选择聊天对象")
        return
      }
      if (this.newMessage.trim() !== '') {
        // 构造消息对象
        const message = {
          sender_id: this.MyId,
          goods_id: this.selectedUser.goods_id,
          receiver_id: this.selectedUser.id,
          type: 'text',
          message: this.newMessage,
        };
        // 发送消息给 WebSocket 服务器
        this.ws.send(JSON.stringify(message));
        // 清空输入框
        this.newMessage = '';
        this.Message.push(message);
      }else{
        this.$message.error("请输入合法字符")
      }

    },
    initWebSocket() {
      // 连接 WebSocket
      this.ws = new WebSocket(`ws://192.168.31.214:1006/channel/admin/${this.MyId}`);
      // 监听 WebSocket 连接打开事件
      this.ws.onopen = () => {
        console.log('WebSocket 连接已打开');
      };

      // 监听 WebSocket 接收到消息事件
      this.ws.onmessage = (event) => {
        const message = JSON.parse(event.data);
        this.Message.push(message);
      };

      // 监听 WebSocket 连接关闭事件
      this.ws.onclose = () => {
        console.log('WebSocket 连接已关闭');
      };

      // 监听 WebSocket 连接错误事件
      this.ws.onerror = (error) => {
        console.error('WebSocket 连接出现错误:', error);
      };
    },
    // 获取聊天记录人员
    initRecordsPeople() {
      const admin_id = this.MyId;
      chatAdmin(admin_id).then(res => {
        console.log("----------------")
        console.log("res:", res)
        console.log("----------------")
        this.contactsList = res.data
      })

    },
    getRecordsByUserId(item) {
      const vm = this
      getAdminMsg(item).then(res => {
        console.log("res:", res)
        vm.Message = res.data
      })
    },
    // 获得自己的ID
    getMyId() {
      let userInfo = localStorage.getItem('userInfo');
      let userInfoJson = JSON.parse(userInfo)
      this.MyId = userInfoJson.id
    },
    // 获取商品信息
    getGoodsById(id) {
      queryGoodsById(id).then(res => {
        this.goodsName = res.data.goodsName
      })
    }
  },

};
</script>

<style land="scss">
.chat-container {
  display: flex;
  height: 100%;
  border: 1px solid #ccc;
  background-color: #fff;
  width: 80%;
  margin: 0px auto;
  box-sizing: border-box;
}

.chat-sidebar {
  width: 15%; /* 左侧聊天人员列表的宽度 */
  border-right: 1px solid #ccc;
}

.selected {
  background-color: #a1d1ef; /* 设置选中项的背景颜色 */
}

.searchBox {
  padding: 15px 10px;
  border-bottom: 1px solid #ccc;

  input {
    box-sizing: border-box;
    width: 100%;
    padding-left: 10px;
    border-radius: 5px;
    height: 40px;
    background-color: #eeeeee;
    border: 0;
    font-size: 15px;
  }
}
.chat-contacts{
  overflow: hidden; /* 超出隐藏 */
  overflow-y: auto; /* 使用滚动条滚动 */
}
.chat-content {
  flex: 1; /* 右侧聊天界面占据剩余空间 */
  position: relative;
  display: flex;
  flex-direction: column;


  .TopName {
    padding: 15px 10px 15px 40px;
    border-bottom: 1px solid #ccc;
    height: 40px;
    line-height: 40px;
    font-size: 25px;
  }
}


.contact {
  cursor: pointer;
  display: flex;
  padding: 10px;
  border-bottom: 1px solid #e1e1e1;
}

.avatar {
  background-color: #7dbeb5;
  color: white;
  height: 50px;
  width: 50px;
  display: flex;
  font-size: 12px;
  justify-content: center;
  align-items: center;
  border-radius: 5px;
}

.name {

  font-size: 20px;
  margin-left: 15px;

  .goodsID {
    font-size: 12px;
    margin-top: 5px;
  }
}


.sendMsgBox {
  margin-top: auto;
  height: 20%;
  border-top: 1px solid #ccc;
}

.type {
  height: 15%;
}

.MsgBox {
  height: 85%;
  position: relative; /* 让按钮相对于父容器定位 */
}

.sendMsgBox textarea {
  width: calc(100% - 100px); /* 宽度减去按钮宽度 */
  height: 100%;
  padding: 10px;
  border: none;
  resize: none;
  box-sizing: border-box;
  font-size: 25px;
  background-color: #ffffff;
  outline: none;
}

.sendButton {
  position: absolute;
  bottom: 10px; /* 距离父容器底部的距离 */
  right: 10px; /* 距离父容器右侧的距离 */
  padding: 5px 10px;
  background-color: #007bff;
  color: #fff;
  border: none;
  cursor: pointer;
  font-size: 16px;
}

.chat-messages {
  overflow-y: auto; /* 当聊天记录过多时自动滚动 */
  height: 80%;
  .goods {
    position: sticky;
    top: 0;
    z-index: 1;
    width: 100%;
    height: 50px;
    background-color: #dedede;
    text-align: center;
    line-height: 50px;
    font-size: 18px;
    color: #ff0000;
  }

  .message {
    width: 100%;
    padding: 0 40px;
    box-sizing: border-box;
    margin-top: 20px;

  }

  .item {
    display: flex;
    margin-top: 10px;
    box-sizing: border-box;
  }

  .avatar-msg {
    width: 50px;
    height: 50px;
    background-color: #7dbeb5;
    margin-bottom: 10px;
    box-sizing: border-box;
    color: white;
    font-size: 12px;
    text-align: center;
    line-height: 50px;
    border-radius: 5px;
  }

  .content {
    margin: 10px;
    max-width: 500px;
    overflow-y: hidden;
    border-radius: 5px;
  }
  .File{
    margin: 10px;
    img{
      width: 300px;
      height: 300px;
      border: 1px solid #000000;
      border-radius: 5px;
    }
  }
  .you {
    justify-content: flex-start;

    .content {
      background-color: #5589b4;
      color: white;

    }
  }

  .me {
    justify-content: flex-end;

    .content {
      background-color: #41831b;
      color: white;
    }
  }
}

</style>
